import 'package:fish_redux/fish_redux.dart';

import 'action.dart';
import 'state.dart';

Reducer<PracticeEditState> buildReducer() {
  return asReducer(
    <Object, Reducer<PracticeEditState>>{
      PracticeEditAction.loading: _loading,
      PracticeEditAction.loaded: _loaded,
      PracticeEditAction.doingOcr: _doingOcr,
      PracticeEditAction.doneOcr: _doneOcr,
      PracticeEditAction.result: _result,
      PracticeEditAction.selectGrade: _selectGrade,
      PracticeEditAction.selectType: _selectType,
    },
  );
}

PracticeEditState _loading(PracticeEditState state, Action action) {
  return state.clone()..isLoading = true;
}

PracticeEditState _loaded(PracticeEditState state, Action action) {
  return state.clone()..isLoading = false;
}

PracticeEditState _selectGrade(PracticeEditState state, Action action) {
  return state.clone()..gradeValue = action.payload;
}

PracticeEditState _selectType(PracticeEditState state, Action action) {
  return state.clone()..typeValue = action.payload;
}

PracticeEditState _doingOcr(PracticeEditState state, Action action) {
  int index = action.payload;
  final PracticeEditState newState = state.clone()..currentOcrIndex = index;
  return newState;
}

PracticeEditState _doneOcr(PracticeEditState state, Action action) {
  final PracticeEditState newState = state.clone();
  Map<String, String> ocr = action.payload;
  var title = ocr['title'];
  if (newState.titleEditController.text.isEmpty) {
    newState.titleEditController.text += title.replaceAll('null', '');
    title = '';
  }
  newState.contentEditController.text += title + ocr['content'];
  if (newState.currentOcrIndex == newState.photos.length - 1) {
    newState.currentOcrIndex += 1;
  }
  return newState;
}

PracticeEditState _result(PracticeEditState state, Action action) {
  final PracticeEditState newState = state.clone()..result = action.payload;
  var title = newState.result['title'];
  newState.titleEditController.text += title.replaceAll('null', '');
  newState.contentEditController.text += newState.result['content'];
  return newState;
}
